package com.cpit.platform.web.controller;

import com.cpit.platform.common.constant.LogConstant;
import com.cpit.platform.common.entity.Result;
import com.cpit.platform.common.utils.ResultUtil;
import com.cpit.platform.dao.RoleRepository;
import com.cpit.platform.dao.UserToRoleRepository;
import com.cpit.platform.dto.OperLog;
import com.cpit.platform.dto.User;
import com.cpit.platform.security.service.UserInfo;
import com.cpit.platform.service.OperLogService;
import com.cpit.platform.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Controller
@RequestMapping(value = "/")
public class LoginController {

    @Value("${index.title}")
    public String title;
    @Autowired
    UserToRoleRepository userToRoleRepository;
    @Autowired
    RoleRepository roleRepository;
    @Autowired
    OperLogService operLogService;
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value("${server.context-path}")
    private String contextPath;
    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping(value = "app/login", method = RequestMethod.POST)
    public Result<User> appLogin(@RequestBody User user) {
        logger.debug("app login user : ", user.getUsername() + "\t" + user.getPassword());

        OperLog operLog = new OperLog();
        operLog.setOperateTime(new Date());
        operLog.setOperateUser(user.getUsername());
        operLog.setCommand(LogConstant.OPER_LOGIN);
        operLog.setModule(LogConstant.MODULE_SECURITY);

        User u = userService.findByUsername(user.getUsername());
        logger.debug("app login get user is : ", u);
        if (!u.getPassword().equals(user.getPassword())) {
            logger.warn("app login error");
            operLog.setResult(Result.CODE_FAILED);
            operLog.setDetail("密码不正确");
            operLogService.writeLog(operLog);
            return new Result(Result.CODE_FAILED, "login error");
        }

        logger.warn("app login successful");
        operLog.setResult(Result.CODE_SUCCESS);
        operLogService.writeLog(operLog);
        return new Result(Result.CODE_SUCCESS, "login successful");
    }

    @RequestMapping(value = "/")
    public String index(Model model) {
        try {
            UserInfo userDetails = (UserInfo) SecurityContextHolder.getContext()
                    .getAuthentication()
                    .getPrincipal();

            logger.debug("login user : {}", userDetails.getUser());

            model.addAttribute("contextPath", contextPath);
            model.addAttribute("indexTitle", title);
            model.addAttribute("user", userDetails.getUser());

        } catch (Exception e) {
            logger.error("path '/' error:", e.getMessage());
        }

        return "platform/index";
    }

    @RequestMapping(value = "/platform/login", method = RequestMethod.GET)
    public String login(Model model) {
        logger.debug("input login()");
        model.addAttribute("indexTitle", title);
        return "platform/login";
    }

    @ApiOperation(value = "查询当前登录用户", notes = "查询浏览器当前的登录用户，如果登录，返回值code为1，且携带登录用户信息，否则则返回值code为2")
    @ResponseBody
    @RequestMapping(value = "/getCurrentUser", method = RequestMethod.GET)
    public Result<UserInfo> getCurrentUser() {
        try {
            UserInfo userDetails = (UserInfo) SecurityContextHolder.getContext()
                    .getAuthentication()
                    .getPrincipal();
            if (userDetails == null) {
                return ResultUtil.error(Result.CODE_FAILED, "无登录用户！");
            } else {
                User user = userDetails.getUser();
                if (user == null) {
                    return ResultUtil.error(Result.CODE_FAILED, "无登录用户！");
                }
                logger.debug("getCurrentUser: ", user);
                return ResultUtil.<UserInfo>success(userDetails);
            }
        } catch (Exception e) {
            return ResultUtil.error(Result.CODE_FAILED, "无登录用户！");
        }
    }

    @ApiOperation(value = "查询当前的会话ID", notes = "查询当前的会话标识。")
    @ResponseBody
    @RequestMapping(value = "/getCurrentSesionId", method = RequestMethod.GET)
    public Result<String> getCurrentSesionId(HttpServletRequest request) {
        try {
            return ResultUtil.error(Result.CODE_SUCCESS, request.getSession().getId());
        } catch (Exception e) {
            return ResultUtil.error(Result.CODE_FAILED, "无登录用户！");
        }
    }


}
